<template>
  <div class="view-fill">
    <div v-if="!showDetails && !detailDialog" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btn-list="fullInfo.btnList"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
              @handleEvent="handleFormEvent"
            >
              <template v-slot:form-receiveIds>
                <el-input
                  v-model="formInfo.data.receiveNames"
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择"
                >
                  <template #append>
                    <el-icon @click="openDeptWindow"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('message_template_content') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template v-slot:filter-addContent>
                <el-button @click="addContent">添加内容</el-button>
              </template>
              <template v-slot:filter-removeContent>
                <el-button
                  :disabled="!canRemoveContent"
                  @click="removeContent()"
                  >删除内容</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <el-form ref="tableForm" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :check-box="true"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-type="scope">
                    <span v-if="scope.row.type == '1'">文本</span>
                    <span v-if="scope.row.type == '2'">占位符</span>
                  </template>
                  <template v-slot:col-urlType="scope">
                    <span v-if="scope.row.urlType == '1'">列表页</span>
                    <span v-if="scope.row.urlType == '2'">详情页</span>
                  </template>
                </page-table>
              </el-form>
            </div>
            <!--选择机构-->
            <select-org
              v-if="orgInfo.visible"
              @callback="callBackDialog"
              @reset="reset"
              v-model:showDialog="orgInfo.visible"
              :query="orgInfo.query"
              :checkBox="true"
              :default-list="formInfo.defaultList"
              :highlightRow="true"
            />
            <!--选择角色-->
            <select-role
              v-if="selectRoleInfo.visible"
              v-model:show-dialog="selectRoleInfo.visible"
              :default-list="formInfo.defaultList"
              :query="selectRoleInfo.query"
              :checkBox="true"
              @callback="callBackDialog"
            />
            <!--选择部门-->
            <SelectDept
              v-if="deptInfo.visible"
              v-model:show-dialog="deptInfo.visible"
              :check-box="true"
              :highlight-row="true"
              :query="deptInfo.query"
              :default-list="formInfo.defaultList"
              :saveEmpty="true"
              @callback="callBackDialog"
            />
            <!--选择人员-->
            <select-users
              v-if="selectUserInfo.visible"
              @callback="callBackDialog"
              v-model:showDialog="selectUserInfo.visible"
              :checkBox="true"
              :checked-list="formInfo.defaultList"
              :highlightRow="true"
            />
            <!-- 新增修改内容弹窗 -->
            <page-dialog
              v-if="dialogInfo.visible"
              :title="dialogInfo.title[dialogInfo.type]"
              v-model:visible="dialogInfo.visible"
              :width="dialogInfo.width"
              :bt-loading="dialogInfo.btLoading"
              :bt-list="dialogInfo.btList"
            >
              <!-- form -->
              <page-form
                class="paddingBox order-model-formBox flex_wrap_start_start"
                v-model:ref-obj="contentFormInfo.ref"
                :data="contentFormInfo.data"
                :field-list="contentFormInfo.fieldList"
                :rules="contentFormInfo.rules"
                :label-width="contentFormInfo.labelWidth"
              />
            </page-dialog>
          </div>
        </div>
      </NewFullScreen>
    </div>
  </div>
</template>

<script setup name="messageTemplateModify">
import SelectOrg from './selectOrg'
import SelectRole from './selectRoles'
import SelectDept from './selectDept'
import SelectUsers from './selectUsers'
import {
  addMessageTemplatePage,
  updateMessageTemplatePage,
} from '@/api/message.js'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps([
  'visible',
  'title',
  'orderId',
  'isSpecialEdit',
  'modifyData',
  'modifyType',
])
const updateRowNum = ref(0)
const formRefs = ref([])
const dialogFormRefs = ref([])
const formInfo = ref({
  ref: null,
  defaultList: [],
  data: {
    receiveType: null,
    receiveNames: '',
    receiveIds: '',
    reminderType: 1,
    messageReceiversType: 'pc,app',
  },
  showDialog: null,
  fieldList: [
    {
      label: '名称',
      value: 'name',
      type: 'input',
      maxlength: 30,
      required: true,
    },
    {
      label: '编码',
      value: 'code',
      type: 'input',
      maxlength: 30,
      required: true,
    },
    {
      label: '消息等级',
      value: 'level',
      type: 'select-model',
      required: true,
      code: 'message_level_type',
      event: 'messageLevelTypeChange',
    },
    {
      label: '提示方式',
      value: 'reminderType',
      type: 'select-model',
      required: true,
      code: 'reminder_type',
      disabled: false
    },
    { label: '标题', value: 'title', type: 'input', maxlength: 30 },
    {
      label: '模板类型',
      value: 'type',
      type: 'select-model',
      required: true,
      multiple: true,
      code: 'message_notification_type',
    },
    {
      label: '消息类型',
      value: 'messageType',
      type: 'select-model',
      required: true,
      code: 'message_type',
    },
    {
      label: '消息接收端',
      value: 'messageReceiversType',
      type: 'select-model',
      required: true,
      disabled: false,
      code: 'message_receivers_type',
      multiple: true,
    },
    {
      label: '接收方类型',
      value: 'receiveType',
      type: 'select-model',
      event: 'cleanReceiveNames',
      code: 'message_recipient_type',
      clearable: true,
      checkDefault: false,
    },
    { label: '接收方', value: 'receiveIds', type: 'slot' },
    {
      label: '三方模板ID',
      value: 'thirdModelId',
      type: 'input',
      maxlength: 100,
      required: true,
      show: false
    },
  ],
  rules: {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    thirdModelId: [{ required: true, message: '请输入三方模板ID', trigger: 'blur' }],
    code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    messageType: [
      { required: true, message: '请选择消息类型', trigger: 'change' },
    ],
    level: [{ required: true, message: '请选择消息等级', trigger: 'change' }],
    type: [{ required: true, message: '请选择模板类型', trigger: 'change' }],
    reminderType: [
      { required: true, message: '请选择提示方式', trigger: 'change' },
    ],
    messageReceiversType: [
      { required: true, message: '请选择消息接收端', trigger: 'change' },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  query: {},
  list: [
    { type: 'slot', value: 'addContent' },
    { type: 'slot', value: 'removeContent' },
  ],
})
// 表格相关
const tableInfo = ref({
  rowKey: 'sort',
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '类型',
      value: 'type',
      type: 'slot',
    },
    {
      label: '内容',
      value: 'content',
    },
    {
      label: '跳转类型',
      value: 'urlType',
      type: 'slot',
    },
    {
      label: '跳转路径',
      value: 'url',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '修改',
        event: updateTable,
        show: true,
      },
    ],
  },
})
// 弹窗相关
const dialogType = ref('')
const dialogInfo = ref({
  title: {
    create: '添加',
    update: '修改',
  },
  visible: false,
  type: '',
  width: '40%',
  btLoading: false,
  btList: [
    { label: '关闭', type: '', icon: '', event: close, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: saveContent,
      saveLoading: false,
      show: true,
    },
  ],
})
// 表单相关
const contentFormInfo = ref({
  ref: null,
  data: {
    type: '',
    content: '',
    urlType: '',
    url: '',
  },
  fieldList: [
    {
      label: '类型',
      value: 'type',
      type: 'select-model',
      code: 'message_content_type',
      required: true,
    },
    {
      label: '内容',
      value: 'content',
      type: 'input',
      maxlength: 100,
      required: true,
    },
    {
      label: '跳转类型',
      value: 'urlType',
      type: 'select-model',
      code: 'message_url_type',
      checkDefault: false,
      event: 'cleanUrl',
      clearable: true,
    },
    {
      label: '跳转路径',
      value: 'url',
      type: 'input',
      maxlength: 100,
      disabled: true,
    },
  ],
  rules: {
    content: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    url: [{ required: false, message: '请输入跳转路径', trigger: 'blur' }],
  },
  labelWidth: '100px',
})
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
const orgInfo = ref({
  visible: false,
  query: {
    idNotIn: '',
    status: 1,
  },
})
const selectRoleInfo = ref({
  visible: false,
  defaultList: [],
  query: {
    orgId: '',
  },
})
const deptInfo = ref({
  visible: false,
  query: {
    orgId: '',
  },
})
const selectUserInfo = ref({
  visible: false,
  saveEmpty: true,
  query: {
    orgId: '',
  },
})
const showSelectOrder = ref(false)
const defaultSelect = ref([])
const detailDialog = ref(false)
const detailId = ref('')
const showDetails = ref(false)
const licenseId = ref('')
const licencesSystemConfig = ref({})
const tableKey = ref(
  'purchApplicationDetailModify-com.slip.spd.entity.vo.purch.PurchApplicationDetailVO'
)
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canRemoveContent = computed(() => {
  return tableInfo.value.selections.length
})

watch(
  () => formInfo.value.data.type,
  (val) => {
    console.log(val)
    // 选择微信 三方显示
    let result = val ? String(val).split(',').includes('1') : false
    formInfo.value.fieldList.find(item => {
      if(item.value === 'thirdModelId'){
        item.show = val ? String(val).split(',').includes('4') : false
      }
      // 不包含站内消息，提示方式、消息接收端 两个框清空且禁止填写  
      if(item.value === 'reminderType'){
        item.disabled = !result
        item.required = result
        formInfo.value.data.reminderType = result ? formInfo.value.data.reminderType : ''
      }
      if(item.value === 'messageReceiversType'){
        item.disabled = !result
        item.required = result
        formInfo.value.data.messageReceiversType = result ? formInfo.value.data.messageReceiversType : ''
      }
    })
    for (const key in formInfo.value.rules) {
      if (Object.hasOwnProperty.call(formInfo.value.rules, key)) {
        if(key === 'reminderType'){
          formInfo.value.rules[key][0].required = result
        }
        if(key === 'messageReceiversType'){
          formInfo.value.rules[key][0].required = result
        }
        
      }
    }

  }
)
watch(
  () => contentFormInfo.value.data.urlType,
  (value) => {
    if (value == '' || value == undefined) {
      contentFormInfo.value.data.url = ''
    }
    if (value) {
      contentFormInfo.value.fieldList.forEach((value) => {
        if (value.value == 'url') {
          value.disabled = false
        }
      })
      contentFormInfo.value.rules.url[0].required = true
    } else
      contentFormInfo.value.fieldList.forEach((value) => {
        if (value.value == 'url') {
          value.disabled = true
        }
      })
    contentFormInfo.value.rules.url[0].required = false
  }
)

onMounted(() => {
  if (props.modifyType == 'update') {
    formInfo.value.data = props.modifyData
    if (formInfo.value.data.receiveType == -2) {
      formInfo.value.data.receiveType = null
    }
    tableInfo.value.data = JSON.parse(props.modifyData.content)
  }
})

function updateTable(val, index) {
  updateRowNum.value = index
  contentFormInfo.value.data = val
  dialogInfo.value.visible = true
  dialogType.value = 'update'
}
function handleFormEvent(val) {
  if (val === 'cleanReceiveNames') {
    formInfo.value.data.receiveNames = ''
    formInfo.value.data.receiveIds = ''
  } else if (val === 'messageLevelTypeChange') {
    if (formInfo.value.data.level === 0) {
      formInfo.value.data.reminderType = 1
    } else {
      formInfo.value.data.reminderType = 2
    }
  }
}
function save() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      if (tableInfo.value.data == null || tableInfo.value.data.length < 1) {
        proxy.$message.error({
          message: '模板内容不能为空！',
          duration: 3000,
          showClose: true,
        })
        return
      }
      formInfo.value.data.content = JSON.stringify(tableInfo.value.data)
      let api =
        props.modifyType == 'create'
          ? addMessageTemplatePage
          : updateMessageTemplatePage
      api(formInfo.value.data).then((res) => {
        if (res.success) {
          showDialog.value = false
          detailDialog.value = false
          emits('returnModify')
        }
      })
    }
  })
}
function close() {
  dialogInfo.value.visible = false
  contentFormInfo.value.data = {}
}
function saveContent() {
  contentFormInfo.value.ref.validate((valid) => {
    if (valid) {
      if (dialogType.value === 'create') {
        tableInfo.value.data.push(contentFormInfo.value.data)
      }
      sortTableData()
      dialogInfo.value.visible = false
    }
  })
}
function sortTableData() {
  if (tableInfo.value.data != null && tableInfo.value.data.length > 0) {
    tableInfo.value.data.forEach((item, index) => (item.id = index.toString()))
  }
}
function reset() {
  orgInfo.value.visible = false
}
function callBackDialog(val) {
  console.log(val, 'kkk')
  if (val != null) {
    let receiveNames = []
    let receiveIds = []
    val.forEach((item) => {
      if (!receiveIds.includes(item.id)) {
        receiveNames.push(item.name)
        receiveIds.push(item.id)
      }
    })
    formInfo.value.data.receiveNames = receiveNames.join(',')
    formInfo.value.data.receiveIds = receiveIds.join(',')
  } else {
    formInfo.value.data.receiveNames = ''
    formInfo.value.data.receiveIds = ''
  }
}
// 触发事件
function handleEvent(event, data) {
  const _tableInfo = tableInfo.value
  switch (event) {
    case 'tableCheck':
      _tableInfo.selections = [...data]
      break
  }
}
function addContent() {
  contentFormInfo.value.data = {}
  dialogInfo.value.visible = true
  dialogType.value = 'create'
}
//删除内容
function removeContent() {
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      tableInfo.value.data = tableInfo.value.data.filter(
        (row) => !tableInfo.value.selections.includes(row)
      )
    })
}
function selectDept(row) {
  if (row) {
    if (row.id !== formInfo.value.data.deptId) {
      formInfo.value.data.deptName = row.name
      formInfo.value.data.deptId = row.deptId
      tableInfo.value.data = []
      defaultSelect.value = []
    }
  } else {
    formInfo.value.data.deptName = ''
    formInfo.value.data.deptId = ''
    tableInfo.value.data = []
    defaultSelect.value = []
  }
}
function openDeptWindow() {
  if (
    formInfo.value.data.receiveType == null ||
    formInfo.value.data.receiveType == ''
  ) {
    proxy.$message.warning({
      message: '请选择接收方类型',
      showClose: true,
      duration: 3000,
    })
  } else {
    let isShowDialog = formInfo.value.data.receiveType
    if (isShowDialog == 1) {
      orgInfo.value.visible = true
    } else if (isShowDialog == 2) {
      selectRoleInfo.value.visible = true
    } else if (isShowDialog == 3) {
      deptInfo.value.visible = true
    } else if (isShowDialog == 4) {
      selectUserInfo.value.visible = true
    }
    let receiveIds = formInfo.value.data.receiveIds
    if (receiveIds) {
      let receiveIdsArray = receiveIds.split(',')
      let receiveIdsArrays = []
      receiveIdsArray.forEach((val) => {
        receiveIdsArrays.push(parseInt(val))
      })
      formInfo.value.defaultList = receiveIdsArrays
    }
  }
}
</script>

<style scoped lang="scss">
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
:deep(.el-table) .nearly-row {
  background: #fceacb;
}
:deep(.el-table) .expire-row {
  background: #f5e4e4;
}
:deep(.el-table__body) tr.hover-row > td {
  background-color: transparent !important;
}
</style>
